package sampler;

import hprose.client.HproseClient;
import hprose.common.HproseResultMode;
import hprose.common.InvokeSettings;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HProseSampler implements JavaSamplerClient {

	private final Logger log = LoggerFactory.getLogger(HProseSampler.class);

	private String url;
	private String method;
	private Object[] params;
	private HproseClient hproseClient;
	private InvokeSettings settings;

	@Override
	public Arguments getDefaultParameters() {

		Arguments params = new Arguments();

		params.addArgument("地址", "tcp/http://......");
		params.addArgument("方法", "远程方法名称");
		params.addArgument("参数", "param1,param2,param3");

		return params;
	}

	@Override
	public void setupTest(JavaSamplerContext context) {

		url = context.getParameter("地址");
		method = context.getParameter("方法");

		// TODO 数据全做字符串存入，此处可能有bug
		String[] ss = context.getParameter("参数").split(",");
		params = new Object[ss.length];
		for (int i = 0; i < ss.length; i++) {
			params[i] = ss[i];
		}

		try {
			hproseClient = HproseClient.create(url);
			settings = new InvokeSettings();
			settings.setMode(HproseResultMode.RawWithEndTag);
		} catch (Throwable e) {
			log.error(e.getMessage(), e);
		}

	}

	@Override
	public SampleResult runTest(JavaSamplerContext context) {

		SampleResult sampleResult = new SampleResult();
		sampleResult.sampleStart();

		try {
			sampleResult.setSamplerData(params.toString());
			String response = (String) hproseClient.invoke(method, new Object[]{"params"}, settings);
			sampleResult.setResponseData(response, "utf-8");
		} catch (Throwable e) {
			log.error(e.getMessage(), e);
		}

		sampleResult.sampleEnd();
		sampleResult.setSuccessful(true);

		return sampleResult;
	}

	@Override
	public void teardownTest(JavaSamplerContext context) {
		// TODO Auto-generated method stub

	}
}
